package com.sfh.base.http.server;

import android.os.Build;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 功能描述:网络层
 *
 * @date 2017/7/18
 */
public class OkHttpClientBuilder implements Interceptor{
    OkHttpClient okHttpClient;
    Retrofit retrofit;
    String hostURL;

    public OkHttpClientBuilder(String hostURL, boolean isDebug){

        this.hostURL = hostURL;
        OkHttpClient.Builder builder = new OkHttpClient.Builder ();
//        if (isDebug) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor ();
            loggingInterceptor.setLevel (HttpLoggingInterceptor.Level.BODY);
            builder.addNetworkInterceptor (loggingInterceptor);
//        }
        builder.addInterceptor (this);
        builder.retryOnConnectionFailure (false);//失败重连
        builder.readTimeout (45 * 1000, TimeUnit.MILLISECONDS);
        builder.connectTimeout (45 * 1000, TimeUnit.MILLISECONDS);
        builder.writeTimeout (45 * 1000, TimeUnit.MILLISECONDS);
        okHttpClient =  builder.build ();
    }

    public Retrofit build(){
        Retrofit.Builder builder = new Retrofit.Builder ();
        builder.addCallAdapterFactory (RxJavaCallAdapterFactory.create ());
        builder.addConverterFactory (GsonConverterFactory.create ());
        builder.baseUrl (this.hostURL);
        builder.client (okHttpClient);
        retrofit =  builder.build ();
        return retrofit;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request;
        if (Build.VERSION.SDK_INT > 13) {
            request = chain.request ()
                    .newBuilder ()
                    .addHeader ("Connection", "close")
                    .build ();
        } else {
            request = chain.request ();
        }
        return chain.proceed (request);
    }
}
